﻿// Copyright 2014 Vincent Perrin
// Use of this source code is governed by a BSD-style license 


function main() {
    console.log("In Main");
    document.querySelector("#MeetNow").addEventListener('click', f_MeetNow, false);
    document.querySelector("#ScheduleMeeting").addEventListener('click', f_ShowSchedule, false);
    //document.querySelector("#button3").addEventListener('click', user, false);
    document.querySelector("#Configure").addEventListener('click', f_ShowSettings, false);
    document.querySelector("#SettingsConfirm").addEventListener('click', f_SettingsConfirm, false);
    document.querySelector("#ConfirmSchedule").addEventListener('click', f_ScheduleConfirm, false);
    document.querySelector('#MeetConfirm').addEventListener('click', f_MeetConfirm, false);
    document.querySelector("#CancelSchedule").addEventListener('click', f_ScheduleCancel, false);


    var cloudaxis_url = "";
    var login = "";
    var pass = "";
    var X_CA_UserName = "";
    var X_CA_Token = "";
    var meeting_name = "";
    var start_time = "";
    var start_date = "";
    var end_time = "";
    var start_meeting = "";
    var end_meeting = "";
    var conference_id = "";
    var meeting_url = "";

    /// Initiate the MeetNow function
    /// Verifies that the credentials are present then creates an AD-HOC Meeting
    function f_MeetNow(e) {
        console.log("Meet Now");

        cloudaxis_url = document.getElementById('cloudaxis_url').value;
        login = document.getElementById('login').value;
        pass = document.getElementById('password').value;
        cloudaxis_url_bkp = localStorage.getItem('CAX_url_save');
        login_bkp = localStorage.getItem('login_save');
        pass_bkp = localStorage.getItem('pass_save');

        if (!cloudaxis_url_bkp && !login_bkp && !pass_bkp) {
            console.log("Cloud AXIS WSP not configured");

            if (!cloudaxis_url && !login && !pass) {
                console.log("Enter Values in Settings");
                document.querySelector("#menu").style.display = 'none'
                document.querySelector("#setup_div").style.display = 'table-cell'
            }
            else {
                make_auth_meetnow(cloudaxis_url, login, pass);
            }
        }
        else {
            make_auth_meetnow(cloudaxis_url_bkp, login_bkp, pass_bkp);
        }
    }

    function f_ShowSchedule(e) {
        console.log("Schedule Meeting");
        document.querySelector("#menu").style.display = 'none'
        document.querySelector("#schedule_div").style.display = 'table-cell'
    }

    function f_ScheduleConfirm(e) {
        console.log("confirm_schedule");
        cloudaxis_url = document.getElementById('cloudaxis_url').value;
        login = document.getElementById('login').value;
        pass = document.getElementById('password').value;
        cloudaxis_url_bkp = localStorage.getItem('CAX_url_save');
        login_bkp = localStorage.getItem('login_save');
        pass_bkp = localStorage.getItem('pass_save');

        meeting_name = document.getElementById('meeting_name').value;
        start_date = document.getElementById('start_date').value;
        start_time = document.getElementById('start_time').value;
        end_time = document.getElementById('end_time').value;

        //need to calculate the offset for the timezone to send the correct time to Cloud AXIS
        var offset = new Date().getTimezoneOffset();  //result will be in minutes off of UTC
        //The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if 
        //the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), 
        //-600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale
        offset = ((offset < 0 ? '+' : '-') + // Note the reversed sign!
          pad(parseInt(Math.abs(offset / 60)), 2) +
          pad(Math.abs(offset % 60), 2));

        start_meeting = start_date + "T" + start_time + ":00.000" + offset;
        end_meeting = start_date + "T" + end_time + ":00.000" + offset;

        

        if (!cloudaxis_url_bkp && !login_bkp && !pass_bkp) {
            console.log("Cloud AXIS WSP not configured");

            if (!cloudaxis_url && !login && !pass) {
                console.log("Enter Values in Settings");
                document.querySelector("#menu").style.display = 'none'
                document.querySelector("#setup_div").style.display = 'table-cell'
            }
            else {
                make_auth_schedule(cloudaxis_url, login, pass);
            }
        }
        else {
            make_auth_schedule(cloudaxis_url_bkp, login_bkp, pass_bkp);

        }
    }

    ///used in order to convert the timezone properly
    function pad(number, length) {
        var str = "" + number
        while (str.length < length) {
            str = '0' + str
        }
        return str
    }

    function f_ScheduleCancel(e) {
        console.log("Schedule Meeting Cancelled");
        document.querySelector("#menu").style.display = 'table-cell'
        document.querySelector("#schedule_div").style.display = 'none'


    }

    function f_ShowSettings(e) {
        console.log("Settings");
        document.querySelector("#menu").style.display = 'none'
        document.querySelector("#setup_div").style.display = 'table-cell'

        cloudaxis_url_bkp = localStorage.getItem('CAX_url_save');
        login_bkp = localStorage.getItem('login_save');
        pass_bkp = localStorage.getItem('pass_save');

        cloudaxis_url = document.getElementById('cloudaxis_url').value;
        login = document.getElementById('login').value;
        pass = document.getElementById('password').value;

        if (!cloudaxis_url_bkp && !login_bkp && !pass_bkp) {
            console.log("Empty Backup");
        }
        else {

            console.log("Backup");
            document.getElementById('cloudaxis_url').value = cloudaxis_url_bkp;
            document.getElementById('login').value = login_bkp;
            document.getElementById('password').value = pass_bkp;
        }
    }

    function f_SettingsConfirm(e) {
        console.log("Confirmation");
        //document.querySelector("#menu").style.display = 'table-cell'
        //document.querySelector("#setup_div").style.display = 'none'

        // Check that the values are not blank.
        //if (!CAX_url_save && !login_save && !pass_save) {
        //    console.log('Error: No value specified');
        //    f_settingsError("<span>Please enter all values</span>");
        //    return;
        //}

        //need to process the username here so that it is accepted by CA
        //store the username as a temporary value
        var login_temp = document.getElementById('login').value;

        //regex to look in the string to find out how many '\' were entered.  CA wants two slashs, most people will only input one '\' So this is error correction to fix that issue.
        var count = login_temp.match(/\\/g);
        //console.log(count);

        if (count === null) {
            //check for user@domain
            count = login_temp.match(/@/g);
            if (count === 1) {
                //the user used the user@domain notation.  CA can handle this just fine, so we proceed after setting the value
                f_SaveValidatedSettings(login_temp);
            } else {
                //check for local user
                //exit out to error screen
                f_settingsError("<span>Username should be in the format of:</span><br /><ol><li>\"user@domain.com\"</li><li>\"domain\\user\"</li></ol>");
            }
        }
        else if (count.length === 2) {
            //user has put username in the format of domain\\user which is exactly what we need...nothing needs to be done here
            console.log(count.length);
            f_SaveValidatedSettings(login_temp);
        } else if (count.length === 1) {
            //double up!
            f_SaveValidatedSettings(login_temp.replace("\\","\\\\"));
        }
        else {
            //user has entered information in some other format...most likely domain\\\user...not going to fix it...just going to make them enter in the correct format
            f_settingsError("<span>Username should be in the format of:</span><br /><ol><li>\"user@domain.com\"</li><li>\"domain\\user\"</li></ol>");
        }

    }

    function f_SaveValidatedSettings(mylogin){
        // Get a value saved in a form.
        var CAX_url_save = document.getElementById('cloudaxis_url').value;
        
        var pass_save = document.getElementById('password').value;
                
        // Save it using the Chrome extension storage API.

        localStorage.setItem('CAX_url_save', CAX_url_save);
        localStorage.setItem('login_save', mylogin);
        localStorage.setItem('pass_save', pass_save);

        document.querySelector("#menu").style.display = 'table-cell'
        document.querySelector("#setup_div").style.display = 'none'


    }

    function f_MeetConfirm(e) {
        console.log("Returning to Main Menu");
        document.getElementById('myAnchor').innerHTML = "";
        document.getElementById('meetnow_span').innerHTML = "";
        document.querySelector("#menu").style.display = 'table-cell'
        document.querySelector("#MeetingDetails_div").style.display = 'none'

    }

    /// Runs the authentication process before MeetNow
    function make_auth_meetnow(cloudaxis_url, login, pass) {
        console.log("Processing Login for Meet Now");

        url_init = "https://" + cloudaxis_url + "/wsp/auth/login";
        console.log(url_init);
        var data = "{" +
                        "\"userName\":\"" + login + "\"," +
                        "\"password\":\"" + pass + "\"" +
                        "}";
        console.log(data);
        var req = new XMLHttpRequest();
        req.open('POST', url_init);
        req.setRequestHeader("Accept", "application/vnd.com.polycom.cloudaxis.userauth+json");
        req.setRequestHeader("Content-Type", "application/vnd.com.polycom.cloudaxis.userauth+json");
        req.withCredentials = false;
        req.send(data);

        req.onreadystatechange = function () {
            if (req.readyState === 4) {
                console.log(req.readyState);
                console.log(req.status);
                if (req.status === 200) {

                    console.error("GOOD !!");
                    var jsonResponse = JSON.parse(req.responseText);
                    //console.log("Auth" + req.responseText);
                    console.log(jsonResponse.userName);
                    console.log(jsonResponse.tokenId);
                    X_CA_UserName = jsonResponse.userName;
                    X_CA_Token = jsonResponse.tokenId;
                    post_meetnow(cloudaxis_url);
                } else {
                    console.error("Something went wrong!");
                    f_errorreport(req.responseText);
                }
            }
        }
    }

    /// Performs the function once the user has been authenticated
    function post_meetnow(CAurl) {
        console.log("Authenticated now creating meeting");
        //auth = make_auth(cloudaxis_url,login,pass);
        var today = new Date();

        startdate = today.toISOString();
        startdate = startdate.substring(startdate.length - 1, startdate) + "+0000";
        console.log(startdate);
        //var data = "{" +
        //    "\"name\":\"" + "Meet Now from Chrome " + "\",\n" +
        //        "\"description\":\"Ad-hoc Meeting\",\n" +
        //        "\"startTime\":\"" + startdate + "\",\n" +
        //        "\"endTime\":\"" + "" + "\",\n" +
        //        "\"createdBy\":{\"userName\":\"" + X_CA_UserName + "\"},\n" +
        //            "\"type\":\"AD_HOC\",\n" +
        //    "\"allowMultipleChairperson\": false,\n" +
        //    "\"authRequired\": true,\n" +
        //    "\"userParticipants\":" + "[{\"userName\":\"" + X_CA_UserName + "\",\"email\":\"vp@p.com\"}]" + "\n" +
        // "}";

        var data = "{\"name\": \"Meet Now from Chrome\", \"description\": \"Ad-hoc Meeting\", \"startTime\": \"" + startdate + "\", \"endTime\": \"\", \"createdBy\": { \"userName\": \"" +
            X_CA_UserName + "\" }, \"type\": \"AD_HOC\", \"allowMultipleChairperson\": false, \"authRequired\": true, \"userParticipants\": [{ \"userName\": \"" + X_CA_UserName + "\" }]}";



        console.log(data);
        url_init = "https://" + CAurl + "/wsp/conferences";
        console.log("URL: " + url_init);
        console.log("X_CA_UserName " + X_CA_UserName);
        console.log("X_CA_Token " + X_CA_Token);

        var req = new XMLHttpRequest();
        req.open('POST', url_init);
        req.setRequestHeader("Accept", "application/vnd.com.polycom.cloudAxis.conference+json");
        req.setRequestHeader("Content-Type", "application/vnd.com.polycom.cloudAxis.conference+json");
        req.setRequestHeader("X-CA-UserName", X_CA_UserName);
        req.setRequestHeader("X-CA-Token", X_CA_Token);
        req.withCredentials = false;
        req.send(data);

        req.onreadystatechange = function () {
            console.log(req.readyState);
            if (req.readyState === 4) {
                console.log(req.status);
                if (req.status === 201) {

                    var jsonResponse = JSON.parse(req.responseText);
                    console.log("Url Conf ID" + jsonResponse.self);
                    conference_id = jsonResponse.self;
                    f_conference_id();

                } else {
                    console.error("Something went wrong!");
                    f_errorreport(req.responseText);

                }
            }

        }
    } // End of Post

    /// Runs the authentication process before the scheduler
    function make_auth_schedule(cloudaxis_url, login, pass) {
        console.log("Processing Login for Scheduler");
        url_init = "https://" + cloudaxis_url + "/wsp/auth/login";
        console.log(url_init);
        var data = "{" +
                        "\"userName\":\"" + login + "\"," +
                        "\"password\":\"" + pass + "\"" +
                        "}";
        console.log(data);
        var req = new XMLHttpRequest();
        req.open('POST', url_init);
        req.setRequestHeader("Accept", "application/vnd.com.polycom.cloudaxis.userauth+json");
        req.setRequestHeader("Content-Type", "application/vnd.com.polycom.cloudaxis.userauth+json");
        req.withCredentials = false;
        req.send(data);

        req.onreadystatechange = function () {
            if (req.readyState === 4) {
                if (req.status === 200) {

                    console.error("GOOD !!");
                    var jsonResponse = JSON.parse(req.responseText);
                    //console.log("Auth" + req.responseText);
                    console.log(jsonResponse.userName);
                    console.log(jsonResponse.tokenId);
                    X_CA_UserName = jsonResponse.userName;
                    X_CA_Token = jsonResponse.tokenId;
                    post_schedule(cloudaxis_url);

                } else {
                    console.error("Something went wrong!");
                    f_errorreport(req.responseText);
                }
            }
        }
    }

    /// Performs the function once the user has been authenticated
    function post_schedule(CAurl) {
        console.log("Performing Meeting Scheduler Functionality");

        var data = "{" +
            "\"name\":\"" + meeting_name + "\",\n" +
                "\"description\":\"Ad-hoc Meeting\",\n" +
                "\"startTime\":\"" + start_meeting + "\",\n" +
                "\"endTime\":\"" + end_meeting + "\",\n" +
                "\"createdBy\":{\"userName\":\"" + X_CA_UserName + "\"},\n" +
                    "\"type\":\"SCHEDULED\",\n" +
            "\"allowMultipleChairperson\": false,\n" +
            "\"authRequired\": true,\n" +
            "\"userParticipants\":" + "[{\"userName\":\"" + X_CA_UserName + "\" }]}";

        console.log(data);

        url_init = "https://" + CAurl + "/wsp/conferences";
        console.log("URL: " + url_init);
        console.log("X_CA_UserName " + X_CA_UserName);
        console.log("X_CA_Token " + X_CA_Token);

        var req = new XMLHttpRequest();
        req.open('POST', url_init);
        req.setRequestHeader("Accept", "application/vnd.com.polycom.cloudAxis.conference+json");
        req.setRequestHeader("Content-Type", "application/vnd.com.polycom.cloudAxis.conference+json");
        req.setRequestHeader("X-CA-UserName", X_CA_UserName);
        req.setRequestHeader("X-CA-Token", X_CA_Token);
        req.withCredentials = false;
        req.send(data);

        req.onreadystatechange = function () {
            if (req.readyState === 4) {
                if (req.status === 201) {

                    var jsonResponse = JSON.parse(req.responseText);
                    console.log("Url Conf ID" + jsonResponse.self);
                    conference_id = jsonResponse.self;
                    f_conference_id();

                } else if (req.status === 400) {
                    //The Meeting Request was not valid.  Report the message to the user
                    f_errorreport(req.responseText);
                } else {
                    console.error("Something went wrong!");
                    console.log(req.responseText);
                }
            }
        }
    } // End of Post

    ///called whenever the meeting setup was not successful
    function f_errorreport(response) {

        var jsonResponse = JSON.parse(response);

        var errorHTML = "<span>" + jsonResponse.errorCode + "</span> <br /> <span>" + jsonResponse.message + "</span>";

        document.querySelector("#menu").style.display = 'none'
        document.querySelector("#schedule_div").style.display = 'none'
        document.getElementById('meetnow_span').innerHTML = errorHTML;
        document.getElementById('myAnchor').innerHTML = "";
        document.querySelector("#MeetingDetails_div").style.display = 'table-cell'
    }

    /// Expecting response as a string
    function f_settingsError(response) {

        document.getElementById('meetnow_title').innerHTML = "<b>Error:</b><br>";

        var errorHTML = "<span>" + response + "</span> <br />";

        document.querySelector("#menu").style.display = 'none'
        document.querySelector("#schedule_div").style.display = 'none'
        document.getElementById('meetnow_span').innerHTML = errorHTML;
        document.getElementById('myAnchor').innerHTML = "";
        document.querySelector("#MeetingDetails_div").style.display = 'table-cell'
    }

    /// Get's the Conference ID for the created Meeting providing the user with a successful message
    function f_conference_id() {
        console.log("conference_id");
        conference_id = conference_id + "/join"
        console.log("URL Conf " + conference_id);

        var xhr = new XMLHttpRequest();
        xhr.open('GET', conference_id);
        xhr.setRequestHeader("X-CA-UserName", X_CA_UserName);
        xhr.setRequestHeader("X-CA-Token", X_CA_Token);
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {

                    document.getElementById('meetnow_title').innerHTML = "<b>Meeting URL:</b><br>";
                    meeting_url = xhr.responseText;
                    console.log("meeting_url: " + meeting_url);
                    document.querySelector("#menu").style.display = 'none'
                    document.querySelector("#schedule_div").style.display = 'none'
                    document.getElementById('myAnchor').innerHTML = meeting_url;
                    document.getElementById('myAnchor').href = meeting_url;
                    document.getElementById('myAnchor').target = "_blank";
                    document.querySelector("#MeetingDetails_div").style.display = 'table-cell'

                } else {
                    console.error("Something went wrong!");
                }
            }
            console.log("Name : " + name);
        };
    }
}

document.addEventListener('DOMContentLoaded', main);